﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace HashFoo.Core
{
    /// <summary>
    /// Provides xml helpers.
    /// </summary>
    public static class XmlUtil
    {
        /// <summary>
        /// Serializes an object to an xml string.
        /// </summary>
        /// <remarks>
        /// Uses default .NET xml serialization infrastructure.
        /// </remarks>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ToXml(this object obj)
        {
            var serializer = new XmlSerializer(obj.GetType());
            var xmlString = new StringBuilder();

            var writer = XmlWriter.Create(
                xmlString,
                new XmlWriterSettings
                {
                    NewLineHandling = NewLineHandling.Replace,
                    Indent = true
                });

            using (writer) serializer.Serialize(writer, obj);

            return xmlString.ToString();
        }

        /// <summary>
        /// Loads (deserializes) an xml string to an object of type T.  Returns null if it can't.
        /// </summary>
        /// <remarks>
        /// Uses default .NET xml serialization infrastructure.
        /// </remarks>
        /// <typeparam name="T"></typeparam>
        /// <param name="xml"></param>
        /// <returns></returns>
        public static T LoadFromXml<T>(string xml)
            where T : class
        {
            var s = new XmlSerializer(typeof(T));
            using (var reader = XmlReader.Create(new StringReader(xml)))
            {
                if (s.CanDeserialize(reader))
                {
                    var obj = s.Deserialize(reader);
                    return obj as T;
                }

                return null;
            }
        }
    }
}